﻿using System.Data;

namespace DataSync.Core
{
    /// <summary>
    /// 比较数据表返回bool
    /// </summary>
    public class DataTableCompare
    {
        public DataTableCompare()
        { }

        /// <summary>
        ///   比较两个DataTable内容是否相等，先是比数量，数量相等就比内容
        /// </summary>
        /// <param name="sourceTable">源表</param>
        /// <param name="targetTable">中间表</param>
        /// <returns></returns>
        public static bool CompareDataTable(DataTable sourceTable, DataTable targetTable)
        {
            //比较行数
            if (sourceTable.Rows.Count == targetTable.Rows.Count)
            {
                //比较字段，数据类型
                if (CompareColumn(sourceTable.Columns, targetTable.Columns))
                {
                    //比较内容
                    for (int i = 0; i < sourceTable.Rows.Count; i++)
                    {
                        for (int j = 0; j < sourceTable.Columns.Count; j++)
                        {
                            if (!sourceTable.Rows[i][j].Equals(targetTable.Rows[i][j]))
                            {
                                return false;
                            }
                        }
                    }
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        ///   <summary>
        ///   比较两个字段集合是否名称,数据类型一致
        ///   </summary>
        ///   <param   name= "sourceTableColumn "> </param>
        ///   <param   name= "middelTableColumn "> </param>
        ///   <returns> </returns>
        private static bool CompareColumn(DataColumnCollection sourceTableColumn, DataColumnCollection middelTableColumn)
        {
            if (sourceTableColumn.Count == middelTableColumn.Count)
            {
                foreach (DataColumn dc in sourceTableColumn)
                {
                    //找相同字段名称
                    if (middelTableColumn.IndexOf(dc.ColumnName) > -1)
                    {
                        //测试数据类型
                        if (dc.DataType != middelTableColumn[middelTableColumn.IndexOf(dc.ColumnName)].DataType)
                        {
                            return false;
                        }
                    }
                    else
                    {
                        return false;
                    }
                }
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}


